for await ... of {javascript}

for await...of is a special kind of loop in JavaScript used to asynchronously iterate over data sources that conform to the async iterable protocol, such as:


✅ Syntax

for await (const item of asyncIterable) {
  // use item
}

This loop:


🧠 When to Use

Use for await...of when:


📦 Example 1: Async Generator

async function* generateNumbers() {
  for (let i = 0; i < 3; i++) {
    await new Promise(res => setTimeout(res, 1000)); // Simulate delay
    yield i;
  }
}

(async () => {
  for await (const num of generateNumbers()) {
    console.log(num); // Prints 0, 1, 2 (1 per second)
  }
})();

📦 Example 2: Reading from a File Stream (Node.js)

import fs from 'fs';
const stream = fs.createReadStream('./bigfile.txt', { encoding: 'utf8' });

for await (const chunk of stream) {
  console.log('Received chunk:', chunk);
}

🧱 Under the Hood


⚠️ Gotchas


Would you like a comparison between for await...of and Promise.all for batching or parallelism?